const User = require('../models/userModel');
const bcrypt = require('bcryptjs');
const db = require('../config/database');

class UserController {
    
    static async updateUserPassword(req, res) {
        try {
            const userId = req.user.userId;
            const { currentPassword, newPassword } = req.body;

            
            const user = await User.findById(userId);
            if (!user) {
                return res.status(404).json({
                    success: false,
                    message: 'User not found'
                });
            }

           
            const isValidPassword = await User.validatePassword(currentPassword, user.password);
            if (!isValidPassword) {
                return res.status(401).json({
                    success: false,
                    message: 'Current password is incorrect'
                });
            }

          
            const hashedPassword = await bcrypt.hash(newPassword, 10);
            const [result] = await db.execute(
                'UPDATE users SET password = ?, updated_at = NOW() WHERE user_id = ?',
                [hashedPassword, userId]
            );

            if (result.affectedRows > 0) {
                res.json({
                    success: true,
                    message: 'Password updated successfully'
                });
            } else {
                res.status(400).json({
                    success: false,
                    message: 'Failed to update password'
                });
            }
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error updating password',
                error: error.message
            });
        }
    }
    
    static async getUserProfile(req, res) {
        try {
            const userId = req.user.userId;
            const user = await User.findById(userId);
            
            if (!user) {
                return res.status(404).json({
                    success: false,
                    message: 'User not found'
                });
            }

            // 不返回密码
            const { password, ...userWithoutPassword } = user;
            
            res.json({
                success: true,
                data: userWithoutPassword
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error fetching user profile',
                error: error.message
            });
        }
    }

    // 更新用户信息
    static async updateUserProfile(req, res) {
        try {
            const userId = req.user.userId;
            const { username, email, currentPassword, newPassword } = req.body;

            // 获取当前用户
            const user = await User.findById(userId);
            if (!user) {
                return res.status(404).json({
                    success: false,
                    message: 'User not found'
                });
            }

            // 如果要修改密码，验证当前密码
            if (newPassword) {
                const isValidPassword = await User.validatePassword(currentPassword, user.password);
                if (!isValidPassword) {
                    return res.status(401).json({
                        success: false,
                        message: 'Current password is incorrect'
                    });
                }
            }
            

            // 构建更新数据
            const updateFields = [];
            const updateValues = [];

            if (username) {
                updateFields.push('username = ?');
                updateValues.push(username);
            }
            if (email) {
                updateFields.push('email = ?');
                updateValues.push(email);
            }
            if (newPassword) {
                updateFields.push('password = ?');
                updateValues.push(await bcrypt.hash(newPassword, 10));
            }

            if (updateFields.length === 0) {
                return res.status(400).json({
                    success: false,
                    message: 'No fields to update'
                });
            }

            // 添加更新时间
            updateFields.push('updated_at = NOW()');

            // 构建完整的 SQL 语句
            const sql = `UPDATE users SET ${updateFields.join(', ')} WHERE user_id = ?`;
            updateValues.push(userId);

            // 执行更新
            const [result] = await db.execute(sql, updateValues);

            if (result.affectedRows > 0) {
                res.json({
                    success: true,
                    message: 'Profile updated successfully'
                });
            } else {
                res.status(400).json({
                    success: false,
                    message: 'Failed to update profile'
                });
            }
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error updating profile',
                error: error.message
            });
        }
    }

    // 获取用户列表（管理员功能）
    static async getUsers(req, res) {
        try {
            const page = parseInt(req.query.page) || 1;
            const limit = parseInt(req.query.limit) || 10;
            const offset = (page - 1) * limit;

            const [rows] = await db.execute(
                'SELECT user_id, username, email, created_at, status FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?',
                [limit, offset]
            );

            // 获取总记录数
            const [count] = await db.execute('SELECT COUNT(*) as total FROM users');
            
            res.json({
                success: true,
                data: rows,
                pagination: {
                    total: count[0].total,
                    page,
                    limit,
                    totalPages: Math.ceil(count[0].total / limit)
                }
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error fetching users',
                error: error.message
            });
        }
    }

    // 更新用户状态（管理员功能）
    static async updateUserStatus(req, res) {
        try {
            const { userId } = req.params;
            const { status } = req.body;

            const [result] = await db.execute(
                'UPDATE users SET status = ? WHERE user_id = ?',
                [status, userId]
            );

            if (result.affectedRows > 0) {
                res.json({
                    success: true,
                    message: 'User status updated successfully'
                });
            } else {
                res.status(404).json({
                    success: false,
                    message: 'User not found'
                });
            }
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error updating user status',
                error: error.message
            });
        }
    }
}

module.exports = UserController; 